/*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~
 * jQuery enhancement
 *~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~
 *  global var
 *~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*/
var NONE_MODE = 0;
var INPUT_MODE = 1;
var SELECTION_MODE = 2;
var current_mode = NONE_MODE;
var input_method_set = [];
var current_im_idx = 0;
/*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~
 *  utility functions
 *~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*/
function logging(s) {
    if (g_debug_enable) {console.log(s);}
}

function util_get_screen_height() {
    return document.documentElement.clientHeight;
}

function util_get_screen_width() {
    return document.documentElement.clientWidth;
}

function util_close_window() {
    window.close();
}

function util_copy_to_clipboard(s) {
    /*
    if(window.clipboardData) {
        window.clipboardData.setData('text',s);
    } else {
        var clipboarddiv=document.getElementById('divclipboardswf');
        if(clipboarddiv==null) {
            clipboarddiv=document.createElement('div');
            clipboarddiv.setAttribute("name", "divclipboardswf");
            clipboarddiv.setAttribute("id", "divclipboardswf");
            document.body.appendChild(clipboarddiv);
        }
        clipboarddiv.innerHTML='<embed src="/ezkeypad/media/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(s)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    }
    alert('The text is copied to your clipboard...');
    //return false;
    */
}
/*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~
 *  other functional functions
 *~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*/
function show_input_panel() {
    arr = im.getInput();
    h = '';
    for (i=0; i<arr.length; i++) {
        h += '<span class="input-char">'+arr[i]+'</span>';
    }
    $('#input-panel').html(h);
}
function show_option_panel() {
    arr = im.getCurrentOption();
    if (arr.length > 0) {
        h = '';
        //h = '';
        for (i=0; i<arr.length; i++) {
            number = (i+1) % im.pagesize;
            h += '<span class="option-char" alt="'+arr[i]+'"><sup class="option-char-index" style="visibility: hidden">'+number+' </sup>'+arr[i]+'</span>';
        }
        //h += '';
        $('#option-panel').html(h);
        
        // add selection interaction
        $('.option-char').click(function () {
            // logging($(this).attr('alt'));
            pre_value = $('#char-result').val();
            $('#char-result').val(pre_value + $(this).attr('alt'));
            if (im.getName() != 'SymbolIM') {
                im.resetContext();
                current_mode = NONE_MODE;
            }
            show_context();
        }).hover(function () {
            $(this).addClass('option-char-border');
        }, function () {
            $(this).removeClass('option-char-border');
        });
    }
    if (im.hasPreviousPage()) {
        $('#previous-page-sign').css({'visibility':'visible'});
    } else {
        $('#previous-page-sign').css({'visibility':'hidden'});
    }
    if (im.hasNextPage()) {
        $('#next-page-sign').css({'visibility':'visible'});
    } else {
        $('#next-page-sign').css({'visibility':'hidden'});
    }
}

function show_context() {
    //logging('current_mode: '+current_mode);
    //logging('input: '+im.getContext()['input']);
    //logging('option: ' + im.getContext()['option']);
    //logging('currentpage: '+im.getContext()['currentpage']);
    //logging('has previous: '+im.hasPreviousPage());
    //logging('has next: '+im.hasNextPage());
    $('#input-panel').html('');
    $('#option-panel').html('');
    
    switch (current_mode) {
    case NONE_MODE:
        if ($('#panel-container').is(':visible')) {
            $('#panel-container').hide('drop', {direction: "down", easing: "easeOutQuint"}, 200);;
        }
        break;
    case INPUT_MODE:
        if ($('#panel-container').css('display') == 'none') {
            $('#panel-container').show('drop', {direction: "down", easing: "easeOutQuint"}, 200);
        }
        show_input_panel();
        show_option_panel();
        break;
    case SELECTION_MODE:
        show_input_panel();
        show_option_panel();
        $('.option-char-index').css({'visibility': 'visible'});
        break;
    default:
        ;
    }
}

function initial_events() {
    $('#copy-result').click(function() {
        // logging('copy-result');
    });
    $('#empty-result').click(function() {
        // logging('empty-result');
        ;
    });
    
    panel_arr = ['button-delete', 'button-ok', 'previous-page', 'next-page'];
    for (i=0; i<panel_arr.length; i++) {
        $('#'+panel_arr[i]).hover(function () {
            $(this).addClass('hand-pointer');
            //$(this).css({'background-image':'url(/ezkeypad/media/key_fw.png)'});
            position_str = $(this).css('background-position');
            x_offset_str = position_str.split(' ')[0];
            x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
            position_str = position_str.substr(x_offset_str.length);
            x_offset = parseInt(x_offset_str)+210;
            position_str = x_offset+position_str;
            $(this).css({'background-position': position_str});
        }, function () {
            $(this).removeClass('hand-pointer');
            //$(this).css({'background-image':'url(/ezkeypad/media/keypad.png)'});
            position_str = $(this).css('background-position');
            x_offset_str = position_str.split(' ')[0];
            x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
            position_str = position_str.substr(x_offset_str.length);
            x_offset = parseInt(x_offset_str)-210;
            position_str = x_offset+position_str;
            $(this).css({'background-position': position_str});            
        });
    }
    
    sel_arr = ['sel-pinyin', 'sel-stroke', 'sel-upperchar', 
        'sel-lowerchar', 'sel-number'];
    for (i=0; i<sel_arr.length; i++) {
        $('#'+sel_arr[i]).click(function () {
            //logging($(this).attr('id'));
            ;
        }).hover(function () {
            $(this).addClass('hand-pointer');
        }, function () {
            $(this).removeClass('hand-pointer');
        });
    }
    
    button_arr = ['button1', 'button2', 'button3', 'button4', 'button5', 'button6', 
        'button7', 'button8', 'button9', 'button0', 'buttonstar', 'buttonwell'];
    for (i=0; i<button_arr.length; i++) {
        $('#'+button_arr[i]).click(function () {
            if (current_mode == SELECTION_MODE) {
                idx = parseInt($(this).attr('id').substr(6));
                if (isNaN(idx) == false) {
                    arr = im.getCurrentOption();
                    idx -= 1;
                    if (idx<0) {idx += im.pagesize};
                    if (undefined != arr[idx]) {
                        pre_value = $('#char-result').val();
                        $('#char-result').val(pre_value + arr[idx]);
                        if (im.getName() != 'SymbolIM') {
                            im.resetContext();
                            current_mode = NONE_MODE;
                        }
                    }
                }
            } else {
                im.processInput($(this).attr('id'));
                im.updateContext();
                c = im.getContext()
                im_name = im.getName()
                if ((im_name == 'StrokeIM') || (im_name == 'UpperCharIM') || (im_name == 'LowerCharIM')) {
                    if (im.getInput().length != 0) {
                        current_mode = INPUT_MODE;
                    }
                } else if (im_name == 'NumberIM') {
                    pre_value = $('#char-result').val();
                    $('#char-result').val(pre_value + c['result']);
                } else if(im_name == 'SymbolIM') {
                    current_mode = INPUT_MODE;
                } else {
                    // do nothing.
                    ;
                }
            }
            show_context();
        }).hover(function () {
            $(this).addClass('hand-pointer');
            //$(this).css({'background-image':'url(/ezkeypad/media/key_fw.png)'});
            position_str = $(this).css('background-position');
            x_offset_str = position_str.split(' ')[0];
            x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
            position_str = position_str.substr(x_offset_str.length);
            x_offset = parseInt(x_offset_str)+210;
            position_str = x_offset+position_str;
            $(this).css({'background-position': position_str});            
        }, function () {
            $(this).removeClass('hand-pointer');
            //$(this).css({'background-image':'url(/ezkeypad/media/keypad.png)'});
            position_str = $(this).css('background-position');
            x_offset_str = position_str.split(' ')[0];
            x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
            position_str = position_str.substr(x_offset_str.length);
            x_offset = parseInt(x_offset_str)-210;
            position_str = x_offset+position_str;
            $(this).css({'background-position': position_str});                        
        });
    }
    
    $('#buttonstar').unbind('click').click(function () {
        current_im_idx = (current_im_idx+1) % input_method_set.length;
        $.cookie('c_current_im_idx', current_im_idx);
        im = input_method_set[current_im_idx];
        $('#im-sign').html(im.getOfficialName());
        if (input_method_set[current_im_idx].getName() == 'SymbolIM') {
            current_mode = INPUT_MODE;
            im.updateContext();
        } else {
            current_mode = NONE_MODE;
        }
        show_context();
        //logging(im.getName());
    });
    
    $('#buttonwell').unbind('click').click(function () {
        pre_val = $('#char-result').val();
        $('#char-result').val(pre_val+' ');
    });
    
    
    $('#previous-page').click(function () {
        switch (current_mode) {
        case NONE_MODE:
            break;
        case INPUT_MODE:
        case SELECTION_MODE:
            im.previousPage();
            break;
        default:
            ;
        }
        show_context();
    });
    $('#next-page').click(function () {
        switch (current_mode) {
        case NONE_MODE:
            break;
        case INPUT_MODE:
        case SELECTION_MODE:
            im.nextPage();
            break;
        default:
            ;
        }
        show_context();
    });
    $('#button-ok').click(function () {
        switch (current_mode) {
        case NONE_MODE:
            break;
        case INPUT_MODE:
            current_mode = SELECTION_MODE;
            break;
        case SELECTION_MODE:
            break;
        default:
            ;
        }
        show_context();
    });
    $('#button-delete').click(function() {
        switch (current_mode) {
        case NONE_MODE:
            // delete the last char of result;
            if (0 != $('#char-result').val().length) {
                s = $('#char-result').val();
                $('#char-result').val(s.substr(0, s.length-1));
            }
            break;
        case INPUT_MODE:
            if (im.getName() != 'SymbolIM') {
                if (im.getContext()['input'].length > 1) {
                    im.deleteInput();
                    im.updateContext();
                } else {
                    im.deleteInput();
                    im.updateContext();
                    current_mode = NONE_MODE;
                }
            } else {
                // delete symbols in result textarea
                if (0 != $('#char-result').val().length) {
                    s = $('#char-result').val();
                    $('#char-result').val(s.substr(0, s.length-1));
                }                
            }
            break;
        case SELECTION_MODE:
            current_mode = INPUT_MODE;
            break;
        default:
            ;
        }
        show_context();
    });
    $('#copy-result').hover(function () {
        $(this).addClass('hand-pointer');
        $(this).css({'background-position':'-108px 0px'});
    }, function () {
        $(this).removeClass('hand-pointer');
        $(this).css({'background-position':'-52px 0px'});
    }).click(function () {
        util_copy_to_clipboard($('#char-result').val());
    });
    $('#empty-result').hover(function () {
        $(this).addClass('hand-pointer');
        $(this).css({'background-position':'-80px 0px'});
    }, function () {
        $(this).removeClass('hand-pointer');
        $(this).css({'background-position':'-24px 0px'});
    }).click(function () {
        $('#char-result').val('');
    });
    
    $('#tip-notify-label').toggle(function () {
        $('#tip-notify').attr('checked', true);
    }, function () {
        $('#tip-notify').attr('checked', false);
    }).hover(function () {
        $(this).addClass('hand-pointer');
    }, function () {
        $(this).removeClass('hand-pointer');
    });
    
    $('#tip-start-service').click(function () {
        $('#model-panel').css({'display': 'none'});
        $('#tip-panel').css({'display': 'none'});
        
        if ($('#tip-notify').attr('checked') == true) {
            $.cookie('c_notify_next_time', '0');
        } else {
            $.cookie('c_notify_next_time', '1');
        }
    });
    $('#tip-close-window').click(function () {
        util_close_window();
    });
    
    $(window).resize(function () {
        $('#main-panel').css({'height':util_get_screen_height()});
        $('#model-panel').css({'height':util_get_screen_height(), 'width':util_get_screen_width()});
    });
}

function initial_style() {
    /*
    // setting screen size 
    min_width = 900;
    min_height = 640;
    if ((document.documentElement.clientWidth<min_width) || (document.documentElement.clientHeight<min_height)) {
        //window.resizeTo(min_width, min_height+80);
        //window.moveTo(0, 0);
    }
    */
    $('#panel-container').css({'display': 'none'});
    $('body').css({'background-color':'#bbc2ee'});
    $('#main-panel').css({'height':util_get_screen_height()});
}

function show_tip_window() {
    // check environment
    //$.browser.msie = true;
    if ((false == $.browser.msie) && (false == $.browser.opera)) {
        $('#tip-env-check').html('<p><span style="color: green;">运行环境检测：通过</span></p>');
        $('#tip-start-service').attr('disabled', false);
    } else {
        $('#tip-notify-panel').css({'display':'none'});
        $('#tip-start-service').attr('disabled', true);
        $('#tip-env-check').html('<p><span style="color: red;">运行环境检测：未通过，请安装：<a href="http://is.gd/v1rp" target="_blank">火狐浏览器</a> 或者 <a href="http://is.gd/v1rb" target="_blank">谷歌浏览器</a></span></p>');
    }
    
    // TODO: check cookies. 
    if ((null == $.cookie('c_notify_next_time')) || ('1' == $.cookie('c_notify_next_time'))) {
        $('#tip-notify').attr('checked', false);
        // set model-pantl style
        $('#model-panel').css({'height':util_get_screen_height(), 
            'width':util_get_screen_width(), 
            'display':'block'});    
        // set tip window style
        w_size = 0.6;
        h_size = 0.6;
        $('#tip-panel').css({'height':util_get_screen_height()*h_size, 
            'width':util_get_screen_width()*w_size, 
            'display':'block',
            'top':util_get_screen_height()*(1-h_size)/2+'px',
            'left':util_get_screen_width()*(1-w_size)/2+'px'});
    }
}

function initial_im() {
    input_method_set = [
        new StrokeIM(),
        new UpperCharIM(),
        new LowerCharIM(),
        new NumberIM(),
        new SymbolIM()
    ];
    
    if (null == $.cookie('c_current_im_idx')) {
        current_im_idx = 0;
    } else {
        current_im_idx = $.cookie('c_current_im_idx') % input_method_set.length;
    }
    
    im = input_method_set[current_im_idx];
    $('#im-sign').html(im.getOfficialName());
    
    if (input_method_set[current_im_idx].getName() == 'SymbolIM') {
        current_mode = INPUT_MODE;
        im.updateContext();
        show_context();
    } else {
        current_mode = NONE_MODE;
    }
}

function initial_service() {
    // initial style
    initial_style();
    // initial button event
    initial_events();
    // initial input method
    initial_im();
    
    show_tip_window();
}
